package com.els;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.List;
import java.util.Properties;
import java.util.Set;

import net.sf.json.JSONObject;

import org.elasticsearch.action.bulk.BulkRequestBuilder;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.client.Client;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.ImmutableSettings;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentFactory;


public class Elastic {
	private Client client;
	private String esUrl;
	private String cluster;
	private String shieldUser;
	public Client getClient() {
		return client;
	}

	public void setClient(Client client) {
		this.client = client;
	}
	public void closeClient() {
		client.close();
	}
	public boolean bulkIndex(String index,String type,List<JSONObject> jsonList,String id){
		BulkRequestBuilder bulkRequest = client.prepareBulk();
		// either use client#prepare, or use Requests# to directly build index/delete requests
		for (int i=0;i<jsonList.size();i++) {
			JSONObject jsonObject=jsonList.get(i);
			String indexId="";
			if(id!=null){
				String[] indexes=id.split("\\|\\|");
				for (String idx : indexes) {
					try {
						indexId+=jsonObject.get(idx)==null?idx:jsonObject.get(idx);
					} catch (Exception e1) {
							// TODO Auto-generated catch block
						System.out.println("null json");
						indexId+=idx;
						continue;
					}
				}
//					indexId=jsonObject.get(id)+"";
				
			}else {
				indexId=null;
			}
			
			
			try {
				XContentBuilder xcb = XContentFactory.jsonBuilder().startObject();
				Set<String> keys = jsonObject.keySet();
				for (String key : keys) {
					xcb.field(key,jsonObject.get(key));
				}
				xcb.endObject();
				bulkRequest.add(client.prepareIndex(index, type, indexId)
				        .setSource(xcb) );
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

		}
		System.out.println("Request Bulk begins");
		TimeValue timout=new TimeValue(60000l);
		BulkResponse bulkResponse = bulkRequest.setTimeout(timout).execute().actionGet();
		System.out.println("Request Bulk end");
		if (bulkResponse.hasFailures()) {
		    // process failures by iterating through each bulk response item
			System.out.println("bulk has failure!");
			return false;
		}else {
			return true;
		}
	}
	

	public Client buildClient() {
		
//		Settings settings = ImmutableSettings.settingsBuilder()
//			.put("client.transport.sniff", true).build();
//		client = new TransportClient(settings)
		Settings settings = ImmutableSettings.builder()
		        .put("cluster.name", cluster)
		        .put("shield.user", shieldUser)
		        .build();
//		client = new TransportClient(settings)
//			.addTransportAddress(new InetSocketTransportAddress(esUrl, 9300))
//			.addTransportAddress(new InetSocketTransportAddress(esUrl, 9301));
		String[] urls=esUrl.split(";");
		TransportClient tClient=new TransportClient(settings);
		for (String url : urls) {
			String ip=url.split(":")[0];
			String port=url.split(":")[1];
			tClient.addTransportAddress(new InetSocketTransportAddress(ip, Integer.parseInt(port)));

		}
		
		client=tClient;
		return client;
	}
	public Elastic() {
		Properties prop =  new  Properties();    
        InputStream in = getClass().getResourceAsStream( "/config.properties" ); 
        try  {    
            prop.load(in);    
            esUrl = prop.getProperty( "es.url" ).trim(); 
            cluster = prop.getProperty( "cluster.name" ).trim(); 
            shieldUser=prop.getProperty( "shield.user" ).trim(); 
        }catch(Exception e){
        	System.out.println("Load config.properties has an error!");
        }
        buildClient();
	}
	public static void main(String[] args) {
		Elastic elastic=new Elastic();
		String id="http://203.0.64.128:8081/zjgy-search/typical/最高人民法院指导案例汇编 （1-52号）之（44-47）.html";
		elastic.getClient()
			.prepareDelete("zjgy_search_case", "case", id)
			.execute().actionGet();
		elastic.closeClient();
	}
}
